const { getList, getDetail, publish, update, del, getCount } = require('../controller/blog') // controller 逻辑
const { SuccessModel, ErrorModel } = require('../model/resModel') // 返回json状态
const { checkLogin, checkAuthor } = require('../utils') // 工具方法

module.exports = async (req, res) => {

  // get 博客列表
  if (req.method === 'GET' && req.path === '/api/blog/list') {
    if (req.query) var { pageSize, currentPage } = req.query
    try {
      // 获取所有博客 博客总数量
      let [result, count] = await Promise.all([
        getList({pageSize, currentPage, meta: { method: 'GET' }}),
        getCount()
      ])
      return new SuccessModel(result, '获取成功', { count })
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }

  // post 获取后台博客列表
  if (req.method === 'POST' && req.path === '/api/blog/list') {
    // 检查登录状态
    const isLogin = checkLogin(req.session.username)
    if (isLogin) return isLogin
    // 获取pageSize currentPage author
    let {body: { pageSize, currentPage }, session: { username: author }} = req
    try {
      // 获取后台博客 用户发表数量
      let [result, allResult] = await Promise.all([
        getList({pageSize, currentPage, meta: { method: 'POST', author}}),
        getList({meta: { method: 'POST', author}})
      ])
      return new SuccessModel(result, '获取成功', { count: allResult.length })
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }

  // get 博客详情
  if (req.method === 'GET' && req.path === '/api/blog/detail') {
    try {
      let result = await getDetail(req.query)
      return new SuccessModel(result, '获取成功')
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }

  // 发布博客
  if (req.method === 'POST' && req.path === '/api/blog/publish') {
    const isLogin = checkLogin(req.session.username)
    if (isLogin) return isLogin
    const isAdmin = checkAuthor(req.session.role)
    if (isAdmin) return isAdmin
    try {
      await publish(req.body, req.session.username)
      return new SuccessModel('发布成功')
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }

  // 更新博客
  if (req.method === 'POST' && req.path === '/api/blog/update') {
    const isLogin = checkLogin(req.session.username)
    if (isLogin) return isLogin
    const isAdmin = checkAuthor(req.session.role)
    if (isAdmin) return isAdmin
    try {
      await update(req.body)
      return new SuccessModel('更新成功')
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }
  
  // 删除博客
  if (req.method === 'POST' && req.path === '/api/blog/del') {
    const isLogin = checkLogin(req.session.username)
    if (isLogin) return isLogin
    const isAdmin = checkAuthor(req.session.role)
    if (isAdmin) return isAdmin
    try {
      await del(req.body)
      return new SuccessModel('删除成功')
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }
}
